package heven.holt.wan.android.paging

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import heven.holt.library.extensions.setPicCenterCrop
import heven.holt.library.widget.xbanner.XBanner
import heven.holt.wan.android.MainFragmentDirections
import heven.holt.wan.android.R
import heven.holt.wan.android.databinding.HeadHomeArticleBannerBinding
import heven.holt.wan.android.model.BannerModel

class HomeHeadBannerAdapter(
    private val bannerList: MutableList<BannerModel>
) :
    RecyclerView.Adapter<HomeHeadBannerAdapter.HomeHeadBannerViewHolder>() {
    private var xBanner: XBanner? = null

    //用于纪录当前滑动到的item
    private var currentItem = 0

    inner class HomeHeadBannerViewHolder(
        val binding: HeadHomeArticleBannerBinding,
    ) : RecyclerView.ViewHolder(binding.root), XBanner.XBannerAdapter {
        init {
            xBanner = binding.xbanner
            xBanner!!.setBannerPlaceholderImg(R.mipmap.ic_empty, ImageView.ScaleType.CENTER_INSIDE)
            xBanner!!.loadImage(this)
            xBanner!!.setOnItemClickListener { _, model, view, _ ->
                if (model !is BannerModel) return@setOnItemClickListener
                val direction = MainFragmentDirections.actionGlobalWebViewFragment(model.url!!)
                view.findNavController().navigate(direction)
            }
        }

        override fun loadBanner(banner: XBanner?, model: Any?, view: View, position: Int) {
            view as ImageView
            model as BannerModel
            view.setPicCenterCrop(model.imagePath)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeHeadBannerViewHolder =
        HomeHeadBannerViewHolder(
            HeadHomeArticleBannerBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )

    override fun onBindViewHolder(holder: HomeHeadBannerViewHolder, position: Int) {
        holder.binding.xbanner.setBannerData(bannerList)
        holder.binding.xbanner.bannerCurrentItem = if (currentItem == -1) 0 else currentItem

    }

    override fun getItemCount(): Int = 1

    fun observerBanners(list: List<BannerModel>?) {
        currentItem = xBanner?.bannerCurrentItem ?: 0
        this.bannerList.clear()
        this.bannerList.addAll(list ?: emptyList())
        notifyItemChanged(0)
    }
}